import { Component, ViewEncapsulation } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FormBuilder, FormGroup, Validator, Validators } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';

import { passwordMatchValidator } from 'utils/index';
import { ApiRequest } from 'service/ApiRequest';

@Component({
    selector: 'findback',
    encapsulation: ViewEncapsulation.Emulated,
    templateUrl: './ResetPwd.html',
    styleUrls: []
  }
)

export class ResetPwdComponent {
  //loading
  private loading: boolean = false;
  //后端错误
  private error: string = '';
  //手机号
  private PhoneNumber:string = '';

  public resetPwdForm:FormGroup;

  constructor(private formBuilder:FormBuilder, private router: Router, private apiRequest:ApiRequest, private route: ActivatedRoute) {

  }

  ngOnInit() {
    this.route.params.subscribe(data => {
      this.PhoneNumber = data["phoneNumber"];
    });

    this.resetPwdForm = this.formBuilder.group({
      PhoneNumber:[this.PhoneNumber, Validators.compose([Validators.required])],
      Password: [null, Validators.compose([Validators.required,Validators.pattern("^.{6,11}$")])],
      PasswordConfirm: [null, Validators.compose([Validators.required])],
    }, { validator: passwordMatchValidator } );
  }

  resetPwd() {
    if(this.resetPwdForm.valid){
      this.loading = true;
      this.apiRequest.resetPasswordByPhoneNumber(this.resetPwdForm.value).then((data) => {
        this.loading = false;
        this.router.navigate(['/index/login']);
        console.log(data)
      }).catch((e) => {
        console.log(e)
        this.loading = false;
        if(e.length && e.length !== 0){
          this.error = e[0];
        }
      });
    }
  }

}
